import * as Koa from 'koa'
import * as low from 'lowdb'
import * as fileAsync from 'lowdb/lib/storages/file-async.js'
import * as lodashId from 'lodash-id'

declare const console

const app = new Koa()
const db = low('db.json', {
  storage: fileAsync
})
db._.mixin(lodashId)

db.defaults({ counts: { visit: 0 } }).write()

app.context.db = db

/*app.use((ctx, next) => {
 const start = new Date().getMilliseconds()
 return next().then(() => {
 const ms = new Date().getMilliseconds() - start
 console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
 })
 })*/

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  ctx.set('Access-Control-Allow-Headers', "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");
  await next()
});

app.use(async (ctx, next) => {
  const start = new Date().getMilliseconds()
  await next()
  const ms = new Date().getMilliseconds() - start
  ctx.set('X-Response-Time', `${ms}ms !`)
})

app.use(async (ctx, next) => {
  const start = new Date().getMilliseconds()
  await next()
  const ms = new Date().getMilliseconds() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms!`)

  console.log(ctx)
  console.log('req', ctx.request)
  console.log('resp', ctx.response)
})

app.use(async ctx => {
  ctx.body = await db.get('counts').update('visit', (v) => v + 1).write()
})

app.on('error', (err, ctx) => {
  console.log('server error', err, ctx)
})

app.listen(3000)
console.log('[demo] start-quick is starting at port 3000')


function getSyncTime() {
  return new Promise((resolve, reject) => {
    try {
      let start = Date.now()
      setTimeout(() => {
        let end = Date.now()
        resolve(end - start)
      }, 500)
    } catch (err) {
      reject(err)
    }
  })
}

async function getSyncData() {
  let time = await getSyncTime()
  let data = `endTime - startTime = ${time}`
  return data
}

async function getData() {
  let data = await getSyncData()
  console.log(data)
}

getData()